<?php
include "exception.php";
include "db.php";
class SSKMySQLException extends SSKCustomException{};
function throw_SSKMySQLException($message = null, $code = 0) {
	throw new SSKMySQLException($message, $code);
}
class MySQL implements IDatabase {
	#TODO: c'è tanto da fare, tante funzioni da wrappare.
	protected $hostname = null;
	protected $username = null;
	protected $password = null;
	protected $dbname = null;
	
	private $connected = false;
	
	public function __construct($hostname,$username,$password,$dbname) {
		$this->hostname=$hostname;
		$this->username=$username;
		$this->password=$password;
		$this->dbname=$dbname;
	}
	public function Connect() {
		if(!$this->connected) {
			if($connection = mysql_connect($this->hostname, $this->username, $this->password) or throw_SSKMySQLException("Can't connect: ".mysql_error(), mysql_errno())) {
				$this->connected=true;
				$select = mysql_select_db($this->dbname,$connessione) or throw_SSKMySQLException("Can't select MySQL Database '".$this->dbname."': ".mysql_error(), mysql_errno());
			}
		} else {
			throw new SSKMySQLException("Already connected.");
		}
	}
	public function Disconnect() {
		if($this->connected) {
			if(mysql_close()) {
				$this->connected=false;
			} else {
				throw new SSKMySQLException("Can't close connection.");
			}
		} else {
			throw new SSKMySQLException("Not connected.");
		}
	}
	public function Query($sql) {
		if($this->connected) {
			$sql=mysql_query($sql) or throw_SSKMySQLException("Can't query: ".mysql_error());
			return $sql;
		} else {
			throw new SSKMySQLException("Not connected.");
		}
	}
	public function Free($res) {
		if($this->connected) {
			mysql_free_result($res);
		} else {
			throw new SSKMySQLException("Not connected.");
		}
	}
	public function FetchRow($result) {
		if($this->connected) {
			$result=mysql_fetch_row($result);
			return $result;
		} else {
			throw new SSKMySQLException("Not connected.");
		}
	}
	public function FetchArray($result, $restype=null) {
		if($this->connected) {
			if($restype) {
				$result=mysql_fetch_array($result,$restype);	
			} else {
				$result=mysql_fetch_array($result);
			}
			return $result;
		} else {
			throw new SSKMySQLException("Not connected.");
		}
	}
	public function FetchAssoc($result) {
		if($this->connected) {
			$result=mysql_fetch_assoc($result);
			return $result;
		} else {
			throw new SSKMySQLException("Not connected.");
		}
	}
	#TODO: più parametri, mysql_fetch_object() non è così limitata. Però ora non ho voglia.
	public function FetchObject($result) {
		if($this->connected) {
			$result=mysql_fetch_object($result);
			return $result;
		} else {
			throw new SSKMySQLException("Not connected.");
		}
	}

	public function isConnected() {
		return $this->connected;
	}
}
?>